package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.CarlaClassicVo;
import com.jdy.haoduoaiteacher.model.CartoonVo;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.widget.CustomCommonDialog;
import com.jdy.haoduoaiteacher.widget.PopWindow;
import com.jdy.haoduoaiteacher.widget.PopWindow.OnMenuClickListener;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;

public class SliderActivity extends BaseActivity implements OnMenuClickListener {

  @InjectView(id = R.id.webView)
  private WebView slider;

  private final static String PREFIX = "xiaoxiaoban:";
  private final static String SEPARATOR = ":";
  private boolean shouldshare;
  private String mUrl;

  // private int[] idArray;

  private int photo_cloud_id;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.slider_webview);

    setTitle("内容展示");

    initView();
  }

  @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
  private void initView() {

    slider.loadDataWithBaseURL("file:///android_res/drawable/", "",
        "text/html", "UTF-8", null);

    shouldshare = getIntent().getBooleanExtra("shouldshare", false);

    if (shouldshare) {

      // Bundle b = this.getIntent().getExtras();
      // idArray = b.getIntArray("idArray");

      photo_cloud_id = getIntent().getIntExtra("photo_cloud_id", 0);

      img_upright.setVisibility(View.VISIBLE);
      img_upright.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          PopWindow popWindow = new PopWindow(SliderActivity.this);
          popWindow.setOnMenuClickListener(SliderActivity.this);
          popWindow.showPopupWindow(img_upright);
        }
      });
    }

    mUrl = getIntent().getStringExtra("link");

    slider.loadUrl(mUrl);

    slider.setWebViewClient(new WebViewClient() {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if (isURLMatching(url)) {
          return true;
        } else {
          return false;
        }
      }

      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
      }

      @Override
      public void onPageFinished(WebView view, String url) {
        notifyLoadingStop();

        dismissLoading();

        setTitle(view.getTitle());
      }

    });

    // slider.setWebChromeClient(new MyWebChromeClient());

    WebSettings settings = slider.getSettings();

    settings.setBuiltInZoomControls(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    // settings.setSavePassword(true);
    settings.setSaveFormData(true);
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setAllowFileAccess(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setSupportZoom(true);// 是否可以缩放，默认true

    // settings.setSupportMultipleWindows(true);
    settings.setPluginState(PluginState.ON);
    settings.setAppCacheEnabled(true);// 是否使用缓存

    slider.requestFocus();
    slider.setScrollBarStyle(0);

    slider.addJavascriptInterface(new Object() {
    }, "interface");

    slider.loadUrl(getIntent().getStringExtra("link"));
  }

  protected boolean isURLMatching(String url) {
    // some logic to match the URL would be safe to have here
    if (url.contains(PREFIX)) {
      parseURL(url);
      return true;
    }
    return false;
  }

  private void parseURL(String url) {
    int length = url.length();

    int prefix = PREFIX.length();

    String subString = url.substring(prefix, length);

    String[] stringArr = subString.split(SEPARATOR);

    int size = stringArr.length;

    // if (size != 4)
    if (size < 2 || url.contains("lexiaobao")) {
      return;
    }

    String type = stringArr[0];
    int id = Integer.valueOf(stringArr[1]);

    Intent intent = new Intent();

    switch (type) {
    case "album":
    case "radio":
    case "cartoon":
      if (size != 4) {
        return;
      }

      int episode0 = Integer.valueOf(stringArr[3]);
      intent.setClass(this, StoryDetailActivity.class);
      intent.putExtra("id", id);
      intent.putExtra("sort", episode0);
      startActivity(intent);
      break;
    case "story":
      toDubDetail(this, id);
      break;
    default:
      return;

    }

  }

  @SuppressWarnings("unused")
  private void toCollectionStoryDetail(final int storyId, final int bannerId) {

    new AsyncTask<Void, Void, ResponseResult>() {

      @Override
      protected void onPostExecute(ResponseResult result) {
        if (result != null && result.isSuccess()
            && Tools.isNotNullStr(result.data)) {

          CartoonVo vo = JsonSerializer.getInstance().deserialize(result.data,
              CartoonVo.class);

          Intent toActivityIntent = new Intent(SliderActivity.this,
              StoryDetailActivity.class);
          toActivityIntent.putExtra("cartoon", vo);
          toActivityIntent.putExtra("banner_id", bannerId);
          toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(toActivityIntent);
          overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        }
      }

      @Override
      protected ResponseResult doInBackground(Void... params) {
        LeUser lu = MyTeacherApp.getInstance().getUserTeacher();

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/catalog/album/" + storyId, param_,
            HttpUtils.TAG_GET_REQUEST);
      }

    }.execute();
  }

  private void toDubDetail(final Context context, final int storyId) {

    new AsyncTask<Void, Void, ResponseResult>() {
      @Override
      protected void onPostExecute(ResponseResult result) {
        if (Tools.isNotEmpty(result) && result.isSuccess()) {
          try {
            JSONObject jsonObject = new JSONObject(result.data);
            CarlaClassicVo ccv = new CarlaClassicVo();
            ccv.id = storyId; // );

            Intent recode = new Intent();
            if (!jsonObject.isNull("name")) {
              ccv.name = jsonObject.get("name").toString();// );
            }

            if (!jsonObject.isNull("lines")) {
              ccv.lines = jsonObject.get("lines").toString(); // );
            }

            if (!jsonObject.isNull("reslen")) {
              ccv.length = Integer
                  .parseInt(jsonObject.get("reslen").toString());// ) // ;
            }

            if (!jsonObject.isNull("url")) {
              ccv.url = jsonObject.get("url").toString(); // );
            }

            if (!jsonObject.isNull("cover")) {
              ccv.cover = jsonObject.get("cover").toString();// );
            }

//            Bundle bundle = new Bundle();
//            bundle.putSerializable("carlaclassic", ccv);
//            recode.putExtras(bundle);
//            recode.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            recode.setClass(context, RecordActivity.class);
//
//            context.startActivity(recode);
          } catch (JSONException e) {

            e.printStackTrace();
          }
        }
      }

      @Override
      protected ResponseResult doInBackground(Void... params) {

        LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL + "/api/story/"
            + storyId, param_, HttpUtils.TAG_GET_REQUEST);

      }

    }.execute();

  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
      if (slider.canGoBack()) {
        slider.goBack();// 返回上一页面
        return true;
      }
    }
    return super.onKeyDown(keyCode, event);
  }

  @Override
  public void onClickShare() {
    Intent intent = new Intent(this, SharePopupWindow.class);
    intent.putExtra("Sharedlink", mUrl);
    startActivity(intent);
  }

  @Override
  public void onClickDelete() {
    CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(this)
        .setMessage("确定要删除吗？删除后不可恢复。").setTitle("删除提示")
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(final DialogInterface dialog, int id) {

            new CustomAsyncTask(SliderActivity.this, new IAsyncTask() {
              @Override
              public void onRecieveData(Activity activity,
                  final ResponseResult arg0) {
                if (arg0.isSuccess()) {
                  dialog.dismiss();
                  finish();
                } else {
                  toastShow(arg0.data);
                }

                dismissLoading();
              }

              @Override
              public ResponseResult doInbackground(Activity activity) {
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                if (lu == null) {
                  lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);

                return HttpUtils.startRequest(HttpUtils.API_URL
                    + "/api/2.0/member/photocloud/" + photo_cloud_id, param_,
                    HttpUtils.TAG_DELETE_REQUEST);
              }
            }).execute();

          }
        });
    cdb.create().show();
  }

  @Override
  public void onClickCancel() {
    // TODO Auto-generated method stub
  }

}
